package com.aizuda.boot.modules.business.performancePlan.controller;

import com.aizuda.boot.modules.business.performancePlan.dto.CollectionPlanGroupResponseDTO;
import com.aizuda.boot.modules.business.performancePlan.dto.CreateCollectionPlanDTO;
import com.aizuda.boot.modules.business.performancePlan.service.impl.CollectionPlanServiceImpl;
import com.aizuda.core.api.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.List;

/**
 * 收款计划 Controller
 */
@Slf4j
@RestController
@RequestMapping("/collection-plan")
@RequiredArgsConstructor
@Validated
@Tag(name = "收款计划管理", description = "收款计划相关接口")
public class CollectionPlanController {

    private final CollectionPlanServiceImpl collectionPlanService;

    @PostMapping("/create")
    @Operation(summary = "创建收款计划", description = "创建合同的收款计划，会先删除该合同的所有收款计划再创建新的")
    public ApiResult<Boolean> createCollectionPlan(@RequestBody CreateCollectionPlanDTO createCollectionPlanDTO) {
        try {
            log.info("开始创建收款计划，合同ID: {}", createCollectionPlanDTO.getContractId());
            boolean result = collectionPlanService.createCollectionPlan(createCollectionPlanDTO);
            
            if (result) {
                log.info("创建收款计划成功，合同ID: {}", createCollectionPlanDTO.getContractId());
                return ApiResult.ok(true);
            } else {
                log.error("创建收款计划失败，合同ID: {}", createCollectionPlanDTO.getContractId());
                return ApiResult.failed("创建收款计划失败");
            }
        } catch (Exception e) {
            log.error("创建收款计划异常，合同ID: {}", createCollectionPlanDTO.getContractId(), e);
            return ApiResult.failed("创建收款计划异常：" + e.getMessage());
        }
    }

    @GetMapping("/detail/{contractId}")
    @Operation(summary = "获取收款计划详情", description = "根据合同ID获取收款计划详情，按计划组分类")
    public ApiResult<List<CollectionPlanGroupResponseDTO>> getCollectionPlanDetail(
            @Parameter(description = "合同ID", required = true)
            @PathVariable @NotNull(message = "合同ID不能为空") Integer contractId) {
        try {
            log.info("获取收款计划详情，合同ID: {}", contractId);
            
            List<CollectionPlanGroupResponseDTO> result = collectionPlanService.getCollectionPlanDetail(contractId);
            
            log.info("获取收款计划详情成功，合同ID: {}, 计划组数量: {}", contractId, result.size());
            return ApiResult.ok(result);
            
        } catch (Exception e) {
            log.error("获取收款计划详情异常，合同ID: {}", contractId, e);
            return ApiResult.failed("获取收款计划详情异常：" + e.getMessage());
        }
    }
}
